<template>
	<gui-page ref="guiPage" :customHeader="true">
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :title="$t('multilingual.prodInspection')" @clickRight="clickRight"
				scanType="1" rightType="1"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<view class="distributed">
				<view class="card-mini">
					<view class="gui-form-item gui-border-b">
						<text class="gui-form-label gui-secondary-text">{{ $t('translationImage.process') }}</text>
						<view class="gui-form-body gui-text-right" style="overflow: visible;">
							<superweiCombox style="text-align: right;" :candidates="data.processList"
								:placeholder="$t('pageTranslation.plsChooseDrop')" :isJSON="true" keyName="text"
								@select="selectProcess" v-model="data.processText"></superweiCombox>
						</view>
					</view>
					<view class="gui-form-item gui-border-b">
						<text class="gui-form-label gui-secondary-text">{{ $t('multilingual.productionLine') }}</text>
						<view class="gui-form-body gui-text-right" style="overflow: visible;">

							<superweiCombox style="text-align: right;" :candidates="data.productLineList"
								:placeholder="$t('pageTranslation.plsChooseDrop')" :isJSON="true"
								keyName="productionLineCode" @select="selectProductLine" v-model="data.productLineId"
								:emptyTips="$t('pageTranslation.pleaseSelectThe')"></superweiCombox>
						</view>
					</view>

					<view class="gui-form-item">
						<text class="gui-form-label gui-secondary-text">{{
							$t('multilingual.amountDefectiveGoods') }}：</text>
						<view class="gui-form-body gui-text-right" style="overflow: visible;">{{ totalNum }}
						</view>
					</view>
				</view>
				
				<scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll">
				<!-- 新添加显示 -->
				<view class="card-mini" v-if="data.checkLocationCodes.length > 0">
					<text>{{ $t('whether.checkLocation') }}：</text>
					<view class="gui-form-item gui-border-b">
						<view class="gui-form-body gui-text-right" style="overflow: visible;">
							<uni-list v-for="(item, index) in data.checkLocationCodes" :key="index"
								@click="select(item)">
								<uni-list-item :title="item.checkLocationName"
									style="margin-right: 40rpx;"></uni-list-item>
								<radio style="margin-top: -60rpx;" :value="data.selectedCheckLocationName"
									:checked="item.checkLocationCode == data.selectedCheckLocationCode"
									@click="select(item)" />
							</uni-list>
						</view>
					</view>
				</view>
				<view class="card-mini" v-if="showMaterial">
					<view class="card-mini-body">
						<view class="card-mini-item " style="display: flex;position: relative;margin-bottom: 20rpx;">
							<text class="mini-item-title" style="width:auto">{{
								$t('distributedEnter.materialCode')
							}}：
							</text>
							<text v-if="!data.change">{{ data.productLineInfo.materialCode||data.productLineInfo.outputMaterialCode }}</text>
							<superweiCombox style="text-align: left;left: 1;padding: 0 !important;"
								:candidates="data.selectList" v-else :placeholder="$t('pageTranslation.plsChooseDrop')"
								:isJSON="true" keyName="text" value="text"
								:defaultValue="data.productLineInfo.outputMaterialCode"
								@select="selectProductionMaterialCode" v-model="data.productLineInfo.materialCode">
							</superweiCombox>
							<text style="margin-left: 30rpx;color: brown;font-weight: 600;"
								v-if="data.productLineInfo.tag">{{
									data.productLineInfo.tag }}</text>
						</view>
						<view class="card-mini-item " style="margin-bottom: 20rpx;">
							<text class="mini-item-title" style="width:100%">{{
								$t('distributedEnter.materialName') }}：{{ data.productLineInfo.materialName ||
									data.productLineInfo.outputMaterialName }}
							</text>
						</view>
						<view class="card-mini-item" style="margin-bottom: 20rpx;">
							<view style="width:100%" class="mini-item-50">
								<text class="mini-item-title">{{ $t('distributedEnter.materialSpec') }}：</text>
								{{ data.productLineInfo.materialSpec || data.productLineInfo.productionMaterialSpec }}
							</view>
						</view>
						<view class="card-mini-item">
							<view style="width:100%;" class="mini-item-50">
								<text class="mini-item-title" style="margin-right: 45rpx;">{{ $t('whether.flowerColor')
								}}：</text>{{ data.productLineInfo.coler || data.productLineInfo.coler }}
							</view>
						</view>
					</view>
				</view>
				<!-- 底部显示区域 -->
					<view class="card-mini" v-if="data.processId && data.defectiveItems.length"
						style="margin-bottom: 120rpx;">
						<view class="card-mini-body">
							<view v-for="(item, index) in data.defectiveItems"
								:key="`${item.productionCheckName}` + `${index}`"
								class="card-mini-item flexcenter gui-space-between" style="font-size: 32rpx;">
								<text>{{ item.productionCheckName }}：</text>
								<uni-number-box v-model="item.number" @change="changeValue" />
							</view>
						</view>
						<view style="height:20rpx"></view>
					</view>
				</scroll-view>
				<view class="page-bottom-box" @click="submit">
					<view class="page-bottomBtn bottomBtn-bgcolor-green">{{ $t('calendar.submit') }}</view>
				</view>
			</view>

			<!-- 弹框 -->
			<uni-popup ref="inputDialog" type="center">
				<view class="input-dialog-box">
					<view class="input-dialog-content" style="height: 300rpx;">
						<view class="gui-form-item gui-border-b">
							<text style="width: 200rpx;">{{ $t('mexico.defectiveLocation') }}：</text>
							<superweiCombox style="text-align: left;" :candidates="data.positionOption"
								:placeholder="$t('pageTranslation.plsChooseDrop')" :isJSON="true" keyName="text"
								@select="change" v-model="data.position2"></superweiCombox>
						</view>
					</view>
					<view class="input-dialog-footer">
						<view class="input-dialog-button" @click="cancelFn">
							{{ $t('popup.cancel') }}
						</view>
						<view class="input-dialog-button dialog-button-left" @click="submit">
							{{ $t('popup.confirm') }}
						</view>
					</view>
				</view>
			</uni-popup>
		</template>
	</gui-page>
</template>
<script setup>
import searchCustom from '@/components/searchCustom';
import superweiCombox from '@/components/superweiCombox';
import calendarCustom from '@/components/calendarCustom';
import uniNumberBox from '@/components/uni-number-box/uni-number-box';

import { ref, reactive, onMounted, getCurrentInstance, computed, watch, watchEffect } from 'vue';

import { findLineByProcessCode, findCheckDataProductTest, commitErrorRecord, getProductionCheckByProcCode, getBomDByProdMaterial } from '@/api/api.js'

import { getDataDictionaryFn, pitchOnFn } from '@/utils/index.js'
import { onShow } from '@dcloudio/uni-app';
import graceJS from "@/Grace6/js/grace.js";
import { navigate } from '@/utils/routerSkip.js';
import { basPdaOperationLogFn } from '@/utils/index.js';
import { OPERATION_COMMIT, USERNAME } from '@/constant/index.js'
//JS国际化引入
import { useI18n } from 'vue-i18n';
components: {
	superweiCombox,
		searchCustom,
		calendarCustom
}

const { t } = useI18n();
let calendarCustomRef = ref(null);
let inputDialog = ref(null)
const { ctx } = getCurrentInstance();

let data = reactive({
	checkLocationCodes: [], // 检验位置
	selectedCheckLocationName: '',
	selectedCheckLocationCode: '',
	defectiveMaterialCode: '',// 次品物料
	defectiveMaterialName: "",
	selectList: [],
	productionMaterialCode: '',
	change: false,
	locations: [], //位置
	processList: [], //工序数据
	processId: '', //用户选中工序
	processText: '', //用户选中工序
	productLineList: [],
	productLineId: '',
	productLineText: '',
	productLineInfo: {},
	defectiveItems: [],
	position: 1,
	position2: '',
	positionOption: [
		// { value: 1, text: t('mexico.JKJOutInput') },
		{ value: 2, text: t('mexico.JKJOutInputLight') }, // JKJOutInputLight-未贴膜
		{ value: 3, text: t('mexico.PEFilm') }, // PE-已贴膜
		// { value: 4, text: t('mexico.PEOutInput') },
	]
});

let totalNum = computed(() => {
	let num = 0;
	data.defectiveItems.forEach(x => {
		num += x.number
	})
	return num
})

//监听
watch(() => data.defectiveItems, (newVal, oldVal) => {
	console.log(newVal)

}, {
	immediate: true,
	deep: true
});


onMounted(() => {
	getInitData()
	changeMaterial()
})
onShow(() => { })

//是否显示物料
/**新加主要是控制次品物料代码显示，如果需要选择位置的，选了位置和产线再显示次品项，不需要选择位置的选了工序和产线就可以显示位置**/
let showMaterial = computed(() => {
	if (data.checkLocationCodes.length == 0) {
		return data.productLineId != ''
	}
	else {
		return (data.selectedCheckLocationName != '' && data.productLineId != '')
	}
})

const select = async (item1) => {
	data.selectedCheckLocationName = item1.checkLocationName
	data.selectedCheckLocationCode = item1.checkLocationCode
	// 修改下拉框物料代码
	for (let i = 0; i < data.selectList.length; i++) {
		const item = data.selectList[i];
		const { code, name, spec } = await dealDefectiveMaterialCode(item.textBak, item.nameBak, item.specBak);
		data.selectList[i].text = code;
		data.selectList[i].name = name;
		data.selectList[i].spec = spec;
	}

	// 修改次品项
	findCheckDataProductTestFn(item1.checkLocationCode);

	// 修改显示的物料特殊处理
	const {
		code,
		name,
		spec
	} = await dealDefectiveMaterialCode(data.productLineInfo.materialCodeBak, data.productLineInfo.materialNameBak, data.productLineInfo.materialSpecBak)

	data.productLineInfo.materialCode = code;
	data.productLineInfo.materialName = name;
	data.productLineInfo.materialSpec = spec;
}

// changeMaterial 数据字典获取直接判断登录人是否在里面
const changeMaterial = async () => {
	let nameList = await getDataDictionaryFn('ChangeMaterial')
	let name = uni.getStorageSync(USERNAME)
	let lsit = nameList.data.filter(x => x.value == name)
	if (lsit.length) {
		data.change = true
	}
}

// 获取工序数据
const getInitData = async () => {
	// 获取调入组织信息
	await getDataDictionaryFn('ProductionProcesses').then(res => {
		if (res.code == 0) {
			res.data.forEach(e => {
				if (e.text == "DR") {
					e.value = "PE"
				}
			})
			data.processList = res.data
		}
	})
	let tepSelect1 = pitchOnFn(data.processList)
	if (tepSelect1.length) {
		data.processId = tepSelect1[0].value
		data.processText = tepSelect1[0].text
		data.processRemark = tepSelect1[0].remark
	}
}

// 用戶修改物料
const selectProductionMaterialCode = (etv) => {
	console.log('-------selectProductionMaterialCode----------', etv);
	data.productLineInfo.materialCode = etv.text
	data.productLineInfo.materialName = etv.name
	data.productLineInfo.materialSpec = etv.spec
	data.productLineInfo.tag = etv.tag
}

// 用户选中工序 
const selectProcess = (etv) => {
	data.defectiveItems = []  //清空数据
	data.processId = etv.value;
	data.processText = etv.text;
	data.productLineList = [];
	data.productLineId = '';
	data.productLineText = '';
	data.selectedCheckLocationCode = "";
	data.selectedCheckLocationName = "";
	if (data.processText == "TH") {
		data.position = 1
	}

	if (data.processText == "JKJ") {
		data.position = 1
	}

	let recordProcessId = data.processId;
	// if (data.processText == "DR") {
	// 	data.position = 4
	// 	data.processId = "PE"
	// }
	if (data.processText == "DR") {
		recordProcessId = "DR"
		data.position = 4
	}
	if (data.processId == "DR") {
		data.processId = "PE"
		data.processText = "PE"
	}

	data.selectedCheckLocationCode = ''
	data.selectedCheckLocationName = ''

	// 调用接口
	getProductionCheckByProcCode({
		procCode: recordProcessId
	}).then(res => {
		console.log(res)
		// 去掉res中data.checkLocationCode 重复字段
		data.checkLocationCodes = res?.filter(x => x.checkLocationCode)?.reduce((acc, current) => {
			const existingIndex = acc.findIndex(
				item => item.checkLocationCode === current.checkLocationCode
			);
			if (existingIndex === -1) {
				acc.push(current);
			}
			return acc;
		}, []) || []
	})
	findLineByProcessCodeFn();
	if (recordProcessId == 'JKJ' || recordProcessId == 'DR'|| recordProcessId == 'LMHH') {
		findCheckDataProductTestFn();
	}
}

// 根据工序查询次品项
const findCheckDataProductTestFn = (checkLocationCode) => {
	findCheckDataProductTest({
		checkProcessCode: data.processId
	}).then(res => {
		if (res.code == 0) {
			data.defectiveItems = res.data;
			console.log('findCheckDataProductTestFn', checkLocationCode)
			if (checkLocationCode) {
				// 根据checkLocationCode过滤结果
				data.defectiveItems = data.defectiveItems.filter(x => x.checkLocationCode == checkLocationCode)
			}
			if (data.processText == "DR") {
				data.defectiveItems = data.defectiveItems.filter(x => x.checkLocationCode == 'FilmAlready')
			}
			data.defectiveItems.forEach(x => {
				x.number = 0
			})
		} else {
			uni.showToast({ title: res.message, icon: 'none' })
		}
	})
}
// 用户选择产线
const selectProductLine = async (etv) => {
	console.log('用户选择产线后', etv)
	data.productLineId = etv.productionLineCode;
	data.productLineText = etv.productionLineName;
	data.productLineInfo = etv;
	data.productionMaterialCode = etv.productionLineCode

	// 根据`选择的校验位置`进行装换
	const {
		code,
		name,
		spec
	} = await dealDefectiveMaterialCode(etv.outputMaterialCode, etv.outputMaterialName, etv.productionMaterialSpec)
	data.productLineInfo.materialCode = code
	data.productLineInfo.materialName = name
	data.productLineInfo.materialSpec = spec
	data.productLineInfo.tag = "Now"

	// 原始字段备份好
	data.productLineInfo.materialCodeBak = etv.outputMaterialCode
	data.productLineInfo.materialNameBak = etv.outputMaterialName
	data.productLineInfo.materialSpecBak = etv.productionMaterialSpec

	// 修改物料下拉选项
	data.selectList = []

	let i = 0
	if (etv.outputMaterialCode) {
		let arr=data.selectList.filter(x=>x.text==code)
		if(!arr.length){
			data.selectList.push({
				value: i++,
				text: code,
				name: name,
				spec: spec,
				textBak: etv.outputMaterialCode,
				nameBak: etv.outputMaterialName,
				specBak: etv.productionMaterialSpec,
				tag: "Now"
			})
		}
	}
	// 上次的条码如果存在,加上上次的
	if (etv.lastMaterialCode) {
		const {
			code,
			name,
			spec
		} = await dealDefectiveMaterialCode(etv.lastMaterialCode, etv.lastMaterialName, etv.lastMaterialSpec)
		let arr=data.selectList.filter(x=>x.text==code)
		if(!arr.length){
			data.selectList.push({
				value: i++,
				text: code,
				name: name,
				spec: spec,
				textBak: etv.lastMaterialCode,
				nameBak: etv.lastMaterialName,
				specBak: etv.lastMaterialSpec,
				tag: 'Last'
			})
		}
	}
}
// 根据用户选中的工序查询产线
const findLineByProcessCodeFn = () => {
	findLineByProcessCode({
		checkProcessCode: data.processId
	}).then(res => {
		if (res.code == 0) {
			data.selectList = []
			data.productLineList = res.data
		} else {
			uni.showToast({ title: res.message, icon: 'none' })
		}
	})
}


/**
 * 次品物料特殊处理
 *  如果当前的检测位置为 THJCError(TH发泡板次品),THLVTError(上基材次品),NoFilm(未贴膜) 需要特殊处理,获取新的物料代码
 * @param code 物料代码
 * @param name 物料名称
 * @returns {Promise<{code, name}|{code: (*|string), name: (*|string)}>}
 */
async function dealDefectiveMaterialCode(code, name, spec) {
	// 检验位置
	let checkLocationCode = data.selectedCheckLocationCode;
	console.log('--------改之前', code, name, spec, checkLocationCode)

	// TH 特殊处理
	let likeCode = ""
	if (checkLocationCode == 'THJCError') {
		likeCode = "4309%"
	} else if (checkLocationCode == 'THLVTError') {
		likeCode = "4319%"
	} else if (checkLocationCode == 'NoFilm') {
		likeCode = "7CK%"
	} else {
		return { code: code, name: name, spec: spec };
	}
	let res = await getBomDByProdMaterial({ itemCode: code, materialCode: likeCode });
	console.log('--------改之后', res)
	return { code: res.data?.code || '', name: res.data?.name || '', spec: res.data?.spec || '' }
}

// 点位选择
const change = (e) => {
	data.position = e.value
	if (data.position == 2) {  //JKJ
		findLineByProcessCode({
			checkProcessCode: 'JKJ'
		}).then(res => {
			if (res.code == 0) {
				var lineList = res.data
				var lineInfo = lineList.filter(e => e.productionLineCode == data.productLineId)[0]
				console.log('lineInfo', lineInfo)
				data.productLineId = lineInfo.productionLineCode;
				data.productLineText = lineInfo.productionLineName;
				data.productLineInfo = lineInfo;
				data.processId = 'JKJ'
				data.processCode = 'JKJ'
				data.processName = 'JKJ'
				data.processText = 'JKJ'

			} else {
				uni.showToast({ title: res.msg, icon: 'none' })
			}
		})
	}
}
// 提交取消
const cancelFn = () => {
	data.position2 = ''
	inputDialog.value.close()
}

// 提交
const submit = () => {
	console.log(data.defectiveItems, 'data.defectiveItems');
	if (!data.processId) {
		uni.showToast({ title: t('JsInternational.chooseOperation'), icon: 'none' })
		return
	}
	if (!data.productLineId) {
		uni.showToast({ title: t('JsInternational.chooseLine'), icon: 'none' })
		return
	}
	if (!data.productLineInfo.outputMaterialCode) {
		uni.showToast({ title: t('JsInternational.productionLine'), icon: 'none' })
		return
	}
	// console.log(totalNum.value, 'totalNumtotalNumtotalNum');
	if (totalNum.value == 0) {
		uni.showToast({ title: t('JsInternational.chooseDefective'), icon: 'none' })
		return
	}
	if (data.position2 == '' && data.processText != 'TH'&& data.processText != 'PE' && data.processText != 'JKJ' && data.processText != 'DR'&& data.processText != 'LMHH') {
		uni.showToast({ title: t('locationBarcodeInfo.pleaseLocations'), icon: 'none' })
		return
	}

	if (data.selectedCheckLocationCode == 'NoFilm') {
		data.processId = 'JKJ'
		data.processCode = 'JKJ'
		data.processName = 'JKJ'
		data.processText = 'JKJ'
	}

	let tepArry = [];
	tepArry = data.defectiveItems.map(x => {
		return {
			productionCheckCode: x.productionCheckCode,
			productionCheckName: x.productionCheckName,
			errorQty: x.number,
		}
	})
	let parmes = {
		processCode: data.processId,
		processName: data.processText,
		productionLineCode: data.productLineId,
		productionLineName: data.productLineText,
		materialCode:data.productLineInfo.materialCode|| data.productLineInfo.outputMaterialCode || data.productLineInfo.productionMaterialCode,
		materialName: data.productLineInfo.materialName ||data.productLineInfo.outputMaterialName || data.productLineInfo.productionMaterialName,
		qmsProductionCheckList: tepArry,
		position: data.position
	}

	// JKJ   DR 工序传checkLocationCod
	if (data.selectedCheckLocationCode == 'NoFilm') {
		parmes.checkLocationCode = data.selectedCheckLocationCode
	} else if (data.processId == 'JKJ' || data.processId == 'DR' || data.processId == 'LMHH') {
		parmes.checkLocationCode = data.processId
	} else {
		parmes.checkLocationCode = data.selectedCheckLocationCode
	}

	uni.showLoading({
		title: t('mexico.systemIsWait'),
		mask: true
	})

	commitErrorRecord(parmes).then(res => {
		uni.hideLoading()
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '生产检验'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_COMMIT,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.code == 0) {
			uni.showToast({ title: t('smashRemoval.submitSuccessfully'), icon: 'none' })
			data.processRemark = ''
			data.processId = ''
			data.processText = ''
			data.productLineId = ''
			data.productLineText = ''
			data.productLineList = []
			data.productLineInfo = {}
			data.defectiveItems = []
			data.selectedCheckLocationCode = "";
			data.selectedCheckLocationName = "";
			data.position2 = ''
			data.checkLocationCodes = []
			inputDialog.value.close()
		} else {
			uni.showToast({ title: res.msg, icon: 'none' })
		}
	}).catch(error => {
		uni.hideLoading()
		uni.showToast({ title: error.data.msg, icon: 'none' })
	})
}


const clickRight = () => {
	navigate({
		url: '/pages/market/checkoutHistory'
	})
}
const goPage = (x) => {
	navigate({
		url: `/pages/market/stockRemovalDetail?id=${x.id}`
	})
}
const changeValue = (e) => {
	console.log(e)
}
</script>
<style lang="scss" scoped>
.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	margin-top: 20rpx;
	margin-bottom: 120rpx;
	height: 2rpx;
}

.nomargintop {
	margin-top: 0px !important;
}

.card-mini-body {
	height: auto !important;
}

.distributed {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
	// height: 100vh;
}

.card-box {
	margin: 0 15rpx;
	box-shadow: 0rpx 0rpx 4rpx 0 #A5A5A5;
	background: #fff;
	padding: 30rpx;
	border-radius: 16rpx;
}

.card-item {
	line-height: 60rpx;
}

.card-bottom {
	margin-bottom: 30rpx;
}

.filtrate-item {
	display: flex;
	align-items: center;
	font-size: 32rpx;
	margin-bottom: 20rpx;

	.filtrate-itemLeft {
		height: 32rpx;
		line-height: 32rpx;
		width: 100rpx;
	}

	.filtrate-itemRight {
		border: 2rpx solid #A5A5A5;
		border-radius: 8rpx;
		overflow: hidden;
		line-height: 40rpx;
		width: 300rpx;
	}
}

// 展开按钮样式
.card-rotating-top {
	margin-top: 30rpx;
}

.addmargin {
	margin-bottom: 30rpx;
}

.mini-item-title {
	font-size: 25rpx;
}

.flexcenter {
	align-items: center;
	height: 90rpx;

	::v-deep .uni-numbox-btns {
		padding: 0 28rpx;
	}

	::v-deep .uni-numbox__value {
		width: 100rpx;
	}
}

.card-selectCustom {
	margin: 0.46875rem 0.625rem;
	box-shadow: 0 0 0.125rem 0 #a5a5a5;
	background: #fff;
	padding: 0.375rem 0.75rem;
	border-radius: 0.5rem;
	position: relative;
	height: 70rpx;
}

.scrollview {
	margin-top: 20rpx;
	padding-bottom: 200rpx;
}

.gui-secondary-text {
	color: #4f4f4f;
}

.gui-form-label {
	width: auto !important;
}

.page-bottom-box {
	position: fixed;
	left: 0px;
	bottom: 0px;
	width: 100%;
}
</style>
